package ca.concordia.soen6461.wichf.dao.memdb;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Table<T> {

	private TableDefinition<T> definition;
	private Map<String, T> records = new HashMap<String, T>();

	public Table(TableDefinition<T> definition) {
		this.definition = definition;
	}

	public TableDefinition<T> getDefinition() {
		return definition;
	}
	
	public void save(T value) {
		records.put(definition.primaryKey(value), value);
	}
	
	public T get(T value) {
		return records.get(definition.primaryKey(value));
	}
	
	public T delete(T value) {
		return records.remove(definition.primaryKey(value));
	}
	
	public List<T> find(Predicate<T> predicate, Comparator<T> order) {
		List<T> result = new ArrayList<T>();
		for (T value : records.values()) {
			if (predicate.matches(value)) {
				result.add(value);
			}
		}
		Collections.sort(result, order);
		return result;
	}

}
